package com.zhkj.txg.module.home.ui

import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.chad.library.adapter.base.entity.node.BaseNode
import com.zhkj.lib.base.ViewModelFragment
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.txg.R
import com.zhkj.txg.module.home.adapter.MallCategoryShopAdapter
import com.zhkj.txg.module.home.vm.MallCategoryViewModel
import kotlinx.android.synthetic.main.fragment_mall_cate.*

@Suppress("UNCHECKED_CAST")
class MallCategoryBrandFragment : ViewModelFragment<MallCategoryViewModel>() {

    companion object {
        private val ID = "id"
        fun getInstance(id: Int): MallCategoryBrandFragment = MallCategoryBrandFragment().apply {
            val bundle = Bundle()
            bundle.putInt(ID, id)
            arguments = bundle
        }
    }

    override fun setViewModel(): MallCategoryViewModel = createViewModel(false)
    override val layoutResId: Int = R.layout.fragment_mall_cate

    private val shopAdapter = MallCategoryShopAdapter().apply {
        loadMoreModule?.isEnableLoadMore = true
        loadMoreModule?.setOnLoadMoreListener {
            viewModel.mallCategory(AccountManager.getToken(), 0)
        }
    }

    override fun initUI() {
        with(rvMallCate) {
            layoutManager = GridLayoutManager(activity, 4)
            adapter = shopAdapter
        }
        shopAdapter.setEmptyView(R.layout.layout_empty_data)
    }

    override fun initViewModel() {
        viewModel.cateId = arguments?.getInt(ID) ?: 0
        viewModel.shopListLiveData.observe(viewLifecycleOwner, Observer { response ->
            when (response.status) {
                HttpResponseStatus.Status.START -> Unit
                HttpResponseStatus.Status.SUCCESS -> response.response?.data?.let {
                    // 判断加载状态
                    if (it.hasMore) shopAdapter.loadMoreModule?.loadMoreComplete()
                    else shopAdapter.loadMoreModule?.loadMoreEnd()
                    // 数据填充
                    if (!it.loadMore) {
                        shopAdapter.setNewData(it.topShop as? MutableList<BaseNode>)
                    }
                    shopAdapter.addData(it.shops)
                }
                HttpResponseStatus.Status.FAILURE -> {
                    response.exception?.printStackTrace()
                    toast(response.statusTip)
                    shopAdapter.loadMoreModule?.loadMoreFail()
                }
            }
        })
    }

    override fun initData() {
        viewModel.mallCategory(AccountManager.getToken(), 0, true)
    }
}